use crate::{Base64Format, Base64Subcommand, get_reader};
use base64::prelude::*;
use std::io::Read;

pub fn base64code(command: Base64Subcommand) -> anyhow::Result<()> {
    match command {
        Base64Subcommand::Decode(opt) => {
            decode(&opt.input, opt.format)?
        }
        Base64Subcommand::Encode(opt) => {
            encode(&opt.input, opt.format)?
        }
    }
    Ok(())
}

fn encode(input: &str, format: Base64Format) -> anyhow::Result<()> {
    let mut reader = get_reader(input)?;
    let mut buf = String::new();
    reader.read_to_string(&mut buf)?;
    let buf = buf.trim();
    let content = match format {
        Base64Format::Standard => BASE64_STANDARD.encode(buf),
        Base64Format::UrlSafe => BASE64_URL_SAFE_NO_PAD.encode(buf),
    };
    println!("{}", content);
    Ok(())
}

fn decode(input: &str, format: Base64Format) -> anyhow::Result<()> {
    let mut reader = get_reader(input)?;
    let mut buf = String::new();
    reader.read_to_string(&mut buf)?;
    let buf = buf.trim();
    let content = match format {
        Base64Format::Standard => BASE64_STANDARD.decode(buf)?,
        Base64Format::UrlSafe => BASE64_URL_SAFE_NO_PAD.decode(buf)?,
    };
    println!("{:?}", String::from_utf8(content)?);
    Ok(())
}


#[cfg(test)]
mod tests {

    //use super::*;

    #[test]
    fn test_encode() {}

    #[test]
    fn test_decode() {}
}